package com.example.woke1;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.silent.handle.CharacterParser;
import com.silent.handle.PinyinComparator;
import com.silent.handle.SideBar;
import com.silent.handle.SideBar.OnTouchingLetterChangedListener;
import com.woke.data.Data_myfriendb;
import com.woke.method.Intentnet;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class PhonefriendaddActivity extends Activity implements OnScrollListener, OnItemClickListener, EasyPermissions.PermissionCallbacks {

	private static final int PHONE_CONTACTS = 26;
	private ListView mListView;
	private ArrayList<String> mContactsName = new ArrayList<String> ();

	private ArrayList<String> mContactsNumber = new ArrayList<String> ();

//	private ArrayList<Bitmap> mContactsPhonto = new ArrayList<Bitmap>();

	private static final String[] PHONES_PROJECTION = new String[]{
			Phone.DISPLAY_NAME, Phone.NUMBER, Phone.PHOTO_ID, Phone.CONTACT_ID};

	private static final int PHONES_DISPLAY_NAME_INDEX = 0;

	private static final int PHONES_NUMBER_INDEX = 1;

	private static final int PHONES_PHOTO_ID_INDEX = 2;

	private static final int PHONES_CONTACT_ID_INDEX = 3;
	private Intent intent;
	private MyApp application;

	private ArrayList<Data_myfriendb> datalist = new ArrayList<Data_myfriendb> ();//ȫ�����
	//	private ArrayList<Data_myfriendb1> listdata = new ArrayList<Data_myfriendb1>();//���������
	private Phoneadater adapter;
	private Intentnet nete;
	private int page = 0;
	String stringss = "";
	private int lastItem;
	private View footview;
	/**
	 */
	private CharacterParser characterParser;
	/**
	 */
	private PinyinComparator pinyinComparator;
	private SideBar sideBar;
	private EditText mEcarno;
	private ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_phonefriend);

		nete = new Intentnet ();
		application = (MyApp) getApplication ();
		intent = getIntent ();
		intview ();

	}

	private void intview() {
		findViewById (R.id.avphonef_image_back).setOnClickListener (new OnClickListener () {

			@Override
			public void onClick(View v) {
				finish ();
			}
		});
		sideBar = (SideBar) findViewById (R.id.sidrbar1);

		sideBar.setOnTouchingLetterChangedListener (new OnTouchingLetterChangedListener () {

			@Override
			public void onTouchingLetterChanged(String s) {

				if(adapter!=null){
					int position = adapter.getPositionForSection(s.charAt(0));
					if (position != -1) {
						mListView.setSelection(position);
					}
				}
			}
		});
		mEcarno = (EditText) findViewById (R.id.avborrowf_edit_search1);
		mEcarno.addTextChangedListener (watcher);

		characterParser = CharacterParser.getInstance ();
		pinyinComparator = new PinyinComparator ();
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage("正在加载中...");

		footview = getLayoutInflater ().inflate (R.layout.footview, null);
		mListView = (ListView) findViewById (R.id.avphonef_listview);
		mListView.addFooterView (footview);
		footview.setVisibility (View.GONE);
		mListView.setOnScrollListener (this);
		mListView.setOnItemClickListener (this);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			methodRequiresTwoPermission ();
		} else {
			getPhoneContacts ();
		}
	}

	private void methodRequiresTwoPermission() {
		String[] perms = {Manifest.permission.READ_CONTACTS,
				Manifest.permission.WRITE_CONTACTS};
		if (EasyPermissions.hasPermissions (this, perms)) {
			getPhoneContacts ();
		} else {
			// Do not have permissions, request them now
			EasyPermissions.requestPermissions (this, "应用需要获取手机通讯录权限",
					PHONE_CONTACTS, perms);
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		super.onRequestPermissionsResult (requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult (requestCode, permissions, grantResults, this);
	}

	@Override
	public void onPermissionsGranted(int requestCode, List<String> perms) {
		if (requestCode == PHONE_CONTACTS) {
			getPhoneContacts ();
		}
	}

	@Override
	public void onPermissionsDenied(int requestCode, List<String> perms) {
		if (requestCode == PHONE_CONTACTS) {
			new AlertDialog.Builder (this).setMessage ("请在<权限管理>里打开手机通讯录权限")
					.setPositiveButton ("前往", new DialogInterface.OnClickListener () {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent (Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							intent.setData (Uri.fromParts ("package", getPackageName (), null));
							startActivity (intent);
							dialog.dismiss ();
						}
					})
					.setNegativeButton ("取消", null)
					.create ()
					.show ();
		}
	}

	private TextWatcher watcher = new TextWatcher () {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			String trim = "" + mEcarno.getText ().toString ().trim ();
			if (trim.equals ("")) {
//	    		mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
			} else {
				int length = trim.length ();
//	    		Log.e("length", ""+length);
				for (int i = 0; i < datalist.size (); i++) {
					if (datalist.get (i).name.length () >= length) {
						if (datalist.get (i).name.substring (0, length).endsWith (trim)) {
							mListView.setSelection (i);
							return;
						}
					}
				}
//	    		mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
			}
		}
	};

	private void getPhoneContacts() {
		//获取手机通讯录
		ContentResolver resolver = getContentResolver ();
		Cursor phoneCursor = resolver.query (Phone.CONTENT_URI,
				PHONES_PROJECTION, null, null, null);

		if (phoneCursor != null) {

			while (phoneCursor.moveToNext ()) {
				String phoneNumber = phoneCursor.getString (PHONES_NUMBER_INDEX);
				if (TextUtils.isEmpty (phoneNumber))
					break;
				if (phoneNumber.length () > 3 && (phoneNumber.startsWith ("+86"))) {
					phoneNumber = phoneNumber.replace ("+86", "");
				}
				Log.e("isMobile",""+nete.isMobile (phoneNumber));
				if (nete.isMobile (phoneNumber)) {
					break;  // 非电话号码,跳过
				}

				String contactName = phoneCursor
						.getString (PHONES_DISPLAY_NAME_INDEX);
				Log.e("phoneCursor2",phoneNumber+"  "+contactName);
				mContactsName.add (contactName);
				mContactsNumber.add (phoneNumber);
//				head, userid, name,type,shouzimu

			}
			phoneCursor.close ();
			if (mContactsNumber.size () <= 100 && mContactsNumber.size () > 0) {
				String strurl1 = mContactsNumber.toString ()
						.substring (1, mContactsNumber.toString ().length () - 1);//弃掉首尾[1,2,3,4]
				sendphonelist (strurl1);
			} else if (mContactsNumber.size () > 100) {
				String strurl1 = mContactsNumber.get (0);
				for (int i = 1; i < 100; i++) {
					strurl1 = strurl1 + "," + mContactsNumber.get (i);
				}
				sendphonelist (strurl1);
			}
		}
	}

	private void addsomeone(String substring, final int position) {
		if (application.getDatas_load () == null) return;
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (PhonefriendaddActivity.this);
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "user");
		params.put ("a", "addPhonefriden");
		params.put ("userid", application.getDatas_load ().getId ());//��ǰ�û�id
		params.put ("phone", substring);
		Log.e ("params", params.toString ());
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				Log.e ("发送", "好友验证" + response);
				try {
					String flag = response.getString ("flag");
					String info = response.getString ("info");
					if (flag.equals ("success")) {
						Toast.makeText (PhonefriendaddActivity.this, "" + info, Toast.LENGTH_SHORT)
								.show ();
						datalist.get (position).type = 4;
						adapter.notifyDataSetChanged ();
					} else {
						Toast.makeText (PhonefriendaddActivity.this, "验证发送失败!", Toast.LENGTH_SHORT)
								.show ();
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
				Log.e ("responseString", "d" + responseString);
			}

			@Override
			public void onStart() {
				super.onStart ();
				if (mProgressDialog != null) {
					mProgressDialog.show();
				}
			}

			@Override
			public void onFinish() {
				super.onFinish ();
				if (mProgressDialog != null) {
					mProgressDialog.dismiss();
				}
			}
		});
	}

	private void sendphonelist(String substring) {
		if (application.getDatas_load () == null) return;
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (PhonefriendaddActivity.this);
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "user");
		params.put ("a", "phoneFridenlist");
		params.put ("phones", substring.replace (" ", ""));
		params.put ("userid", application.getDatas_load ().getId ());
		Log.e ("params", params.toString ());
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				Log.e ("上传", "手机号" + response);
				try {
					String flag = response.getString ("flag");
					if (flag.equals ("success")) {
						JSONObject object = response.getJSONObject ("data");
						JSONArray array = object.getJSONArray ("data");
						for (int i = 0; i < array.length (); i++) {
							JSONObject jsonObject = array.getJSONObject (i);
							String user_login = jsonObject.getString ("user_login");
							int status = jsonObject.getInt ("status");
							String name = mContactsName.get (i);
//							String name = mContactsName.get (datalist.size ());
							Log.e ("name", name);

							String shouzimu = "";

							String pinyin = characterParser.getSelling (name);
							String sortString = pinyin.substring (0, 1).toUpperCase ();

							if (sortString.matches ("[A-Z]")) {
								shouzimu = sortString.toUpperCase ();
							} else {
								shouzimu = "#";
							}
							Data_myfriendb list = new Data_myfriendb ("", user_login, name, status, shouzimu);
							datalist.add (list);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}

				Collections.sort (datalist, pinyinComparator);
				if (datalist.size () <= 100) {
					adapter = new Phoneadater ();
					mListView.setAdapter (adapter);
				} else if (datalist.size () > page * 100) {
					adapter.notifyDataSetChanged ();
					page = page + 1;
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
				Log.e ("上传", "手机号失败" + responseString);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart ();
				if (mProgressDialog != null) {
					mProgressDialog.show();
				}
			}

			@Override
			public void onFinish() {
				super.onFinish ();
				if (mProgressDialog != null) {
					mProgressDialog.dismiss();
				}
				footview.setVisibility (View.GONE);
			}
		});
	}

	class Phoneadater extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return datalist.size ();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		/**
		 * ���ListView�ĵ�ǰλ�û�ȡ���������ĸ��Char asciiֵ
		 */
		public int getSectionForPosition(int position) {
			return datalist.get (position).shouzimu.charAt (0);
		}

		/**
		 * ��ݷ��������ĸ��Char asciiֵ��ȡ���һ�γ��ָ�����ĸ��λ��
		 */
		public int getPositionForSection(int section) {
			for (int i = 0; i < getCount (); i++) {
				String sortStr = datalist.get (i).shouzimu;
				char firstChar = sortStr.toUpperCase ().charAt (0);
				if (firstChar == section) {
					return i;
				}
			}

			return - 1;
		}

		public class Holder {
			TextView username, catalog1;
			ImageView yaoqing;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {

			Holder holder = null;
			if (convertView == null) {
				holder = new Holder ();
				convertView = getLayoutInflater ().inflate (R.layout.item_phonef_adter, null);
				holder.username = (TextView) convertView.findViewById (R.id.item_phonef_name);
				holder.yaoqing = (ImageView) convertView.findViewById (R.id.item_phonef_yaoqing);
				holder.catalog1 = (TextView) convertView.findViewById (R.id.catalog1);
				convertView.setTag (holder);
			} else {
				holder = (Holder) convertView.getTag ();
			}
			final Data_myfriendb phonefried = datalist.get (position);
			// ���position��ȡ���������ĸ��Char asciiֵ
			int section = getSectionForPosition (position);

			// ���ǰλ�õ��ڸ÷�������ĸ��Char��λ�� ������Ϊ�ǵ�һ�γ���
			if (position == getPositionForSection (section)) {
				holder.catalog1.setVisibility (View.VISIBLE);
				holder.catalog1.setText (phonefried.shouzimu);
			} else {
				holder.catalog1.setVisibility (View.GONE);
			}

//			Data_phonefried phonefried = datalist.get(position);
			final int type = phonefried.type;
			holder.username.setText (phonefried.name);
			if (type == 1) {
				holder.yaoqing.setImageDrawable (getResources ().getDrawable (R.drawable.avphonef_right1));
			} else if (type == 2) {
				holder.yaoqing.setImageDrawable (getResources ().getDrawable (R.drawable.avphonef_right2));
			} else if (type == 3) {
				holder.yaoqing.setImageDrawable (getResources ().getDrawable (R.drawable.avphonef_right3));
			} else if (type == 4) {
				holder.yaoqing.setImageDrawable (getResources ().getDrawable (R.drawable.avphonef_agree3));
			}

			holder.yaoqing.setOnClickListener (new OnClickListener () {

				@Override
				public void onClick(View v) {
					if (type == 1) {
						Uri smsToUri = Uri.parse ("smsto://" + phonefried.userid);
						Intent mIntent = new Intent (android.content.Intent.ACTION_SENDTO, smsToUri);
						mIntent.putExtra ("sms_body", getResources().getString(R.string.oem_friend_tuijian));
						startActivity (mIntent);
//						Toast.makeText(PhonefriendaddActivity.this, "���޷�����", Toast.LENGTH_SHORT).show();
					} else if (type == 2) {
						addsomeone (phonefried.userid, position);
					} else {

					}
				}
			});

			return convertView;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		lastItem = firstVisibleItem + visibleItemCount - 1;  //��1����Ϊ������˸�addFooterView
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (datalist == null || datalist.size () == 0) return;
		int size = datalist.size ();
		if (lastItem >= (datalist.size ()) && mContactsNumber.size () > size && scrollState == this.SCROLL_STATE_IDLE) {

			if (mContactsNumber.size () > size + 100) {
				String strurl = mContactsNumber.get (datalist.size () + 1);
				for (int i = 1; i < 100; i++) {
					strurl = strurl + "," + mContactsNumber.get (size + i);
					Log.e ("i", "" + i);
				}
				sendphonelist (strurl);
			} else {
				String strurl = mContactsNumber.get (size + 1);
				for (int i = 1; i < mContactsNumber.size () - size - 1; i++) {
					strurl = strurl + "," + mContactsNumber.get (size + i);
				}
				sendphonelist (strurl);
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	}
}
